/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package cz.muni.fi.pa165.machineryrental.restclient.dialogs;

import cz.muni.fi.pa165.machineryrental.dto.MachineDTO;
import cz.muni.fi.pa165.machineryrental.restclient.services.MachineRestService;
import cz.muni.fi.pa165.machineryrental.restclient.services.MachineRestServiceImpl;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 *
 * @author huzvak
 */
public class MachineDialog extends javax.swing.JDialog {

    private MachineDTO machine;
    private boolean dialogResult;
    private boolean editable;

    /**
     * Creates new form AddNewMachineDialog
     */
    public MachineDialog(java.awt.Frame parent, boolean modal, MachineDTO machine, boolean editable) {

        super(parent, modal);
        initComponents();

        if (machine == null) {
            throw new NullPointerException("machine is null");
        }

        this.editable = editable;

        this.machine = machine;
        this.setValues(machine);

        this.headerLabel.setText(machine.getId() <= 0 ? "Add machine" : "Edit machine");

        codeField.setEditable(editable);
    }

    public MachineDialog(MachineDTO machine, boolean editable) {
        super();
        initComponents();

        if (machine == null) {
            throw new NullPointerException("machine is null");
        }

        this.editable = editable;

        this.machine = machine;
        this.setValues(machine);

        this.headerLabel.setText(machine.getId() <= 0 ? "Add machine" : "Edit machine");

        codeField.setEditable(editable);
    }

    private void setValues(MachineDTO machine) {
        this.codeField.setText(machine.getCode());
        this.brandField.setText(machine.getBrand());
        this.modelField.setText(machine.getModel());
        if (machine.getYearOfProduction() != null) {
            this.yearField.setText(new SimpleDateFormat("dd.MM.yyyy").format(machine.getYearOfProduction()));
        }
    }

    public boolean getDialogResult() {
        return this.dialogResult;
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        headerLabel = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        codeField = new javax.swing.JTextField();
        jLabel3 = new javax.swing.JLabel();
        brandField = new javax.swing.JTextField();
        modelField = new javax.swing.JTextField();
        yearField = new javax.swing.JTextField();
        jLabel4 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        submitBtn = new javax.swing.JButton();
        cancelBtn = new javax.swing.JButton();
        codeErrLbl = new javax.swing.JLabel();
        brandErrLbl = new javax.swing.JLabel();
        modelErrLbl = new javax.swing.JLabel();
        yearErrLbl = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setResizable(false);

        headerLabel.setText("Add new machine");

        jLabel2.setText("Code *");

        jLabel3.setText("Brand *");

        jLabel4.setText("Model *");

        jLabel5.setText("Year of production *");

        submitBtn.setText("Submit");
        submitBtn.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                submitBtnMouseClicked(evt);
            }
        });
        submitBtn.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                submitBtnActionPerformed(evt);
            }
        });

        cancelBtn.setText("Cancel");
        cancelBtn.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                cancelBtnMouseClicked(evt);
            }
        });

        codeErrLbl.setForeground(new java.awt.Color(255, 0, 51));
        codeErrLbl.setText(" ");

        brandErrLbl.setForeground(new java.awt.Color(255, 0, 51));
        brandErrLbl.setText(" ");

        modelErrLbl.setForeground(new java.awt.Color(255, 0, 51));
        modelErrLbl.setText(" ");

        yearErrLbl.setForeground(new java.awt.Color(255, 0, 51));
        yearErrLbl.setText(" ");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(145, 145, 145)
                        .addComponent(headerLabel))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(28, 28, 28)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                                .addComponent(jLabel2)
                                .addGap(111, 111, 111))
                            .addGroup(layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(jLabel5)
                                    .addComponent(jLabel4)
                                    .addComponent(jLabel3))
                                .addGap(18, 18, 18)))
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(yearField)
                            .addComponent(modelField)
                            .addComponent(brandField)
                            .addComponent(codeField, javax.swing.GroupLayout.DEFAULT_SIZE, 276, Short.MAX_VALUE)
                            .addComponent(codeErrLbl, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(brandErrLbl, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(modelErrLbl, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(yearErrLbl, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))))
                .addGap(25, 25, 25))
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(cancelBtn)
                    .addComponent(submitBtn, javax.swing.GroupLayout.PREFERRED_SIZE, 84, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(42, 42, 42))
        );

        layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {brandField, codeField, modelField, yearField});

        layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {cancelBtn, submitBtn});

        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(18, 18, 18)
                .addComponent(headerLabel)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(codeErrLbl)
                .addGap(4, 4, 4)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(codeField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(brandErrLbl)
                .addGap(4, 4, 4)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(brandField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel3))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(modelErrLbl)
                .addGap(4, 4, 4)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(modelField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel4))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(yearErrLbl)
                .addGap(4, 4, 4)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(yearField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel5))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 12, Short.MAX_VALUE)
                .addComponent(submitBtn)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(cancelBtn)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void submitBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_submitBtnActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_submitBtnActionPerformed

    private void submitBtnMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_submitBtnMouseClicked

        String brand = this.brandField.getText();
        String model = this.modelField.getText();
        String code = this.codeField.getText();
        String year = this.yearField.getText();

        boolean hasError = false;

        MachineRestService service = new MachineRestServiceImpl();

        if (brand == null || brand.isEmpty()) {
            brandErrLbl.setText("Brand is required!");
            hasError = true;
        } else {
            brandErrLbl.setText(" ");
        }

        if (model == null || model.isEmpty()) {
            modelErrLbl.setText("Model is required!");
            hasError = true;
        } else {
            modelErrLbl.setText(" ");
        }

        if (editable) {
            if (code == null || code.isEmpty()) {
                codeErrLbl.setText("Code is required!");
                hasError = true;
            } else if (!service.isCodeUnique(code)) {
                codeErrLbl.setText("Given code is already used");
                hasError = true;
            } else {
                codeErrLbl.setText(" ");
            }
        }

        Date date = null;
        if (year == null || year.isEmpty()) {
            yearErrLbl.setText("Year is required!");
            hasError = true;

        } else {
            boolean errorInDate = false;

            SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy");

            try {
                date = sdf.parse(year);
            } catch (ParseException ex) {
                yearErrLbl.setText("Year has to be of format dd.MM.yyyy!");
                hasError = true;
                errorInDate = true;
            }

            if (!errorInDate) {
                yearErrLbl.setText(" ");
            }
        }

        if (hasError) {
            return;
        }

        this.machine.setBrand(brand);
        this.machine.setCode(code);
        this.machine.setModel(model);
        this.machine.setYearOfProduction(date);

        this.dialogResult = true;
        this.dispose();
    }//GEN-LAST:event_submitBtnMouseClicked

    private void cancelBtnMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_cancelBtnMouseClicked
        this.dispose();
    }//GEN-LAST:event_cancelBtnMouseClicked
    /**
     * @param args the command line arguments
     */
//    public static void main(String args[]) {
//        /* Set the Nimbus look and feel */
//        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
//        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
//         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
//         */
//        try {
//            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
//                if ("Nimbus".equals(info.getName())) {
//                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
//                    break;
//                }
//            }
//        } catch (ClassNotFoundException ex) {
//            java.util.logging.Logger.getLogger(MachineDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
//        } catch (InstantiationException ex) {
//            java.util.logging.Logger.getLogger(MachineDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
//        } catch (IllegalAccessException ex) {
//            java.util.logging.Logger.getLogger(MachineDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
//        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
//            java.util.logging.Logger.getLogger(MachineDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
//        }
//        //</editor-fold>
//
//        /* Create and display the dialog */
//        java.awt.EventQueue.invokeLater(new Runnable() {
//            public void run() {
//                MachineDialog dialog = new MachineDialog(new javax.swing.JFrame(), true);
//                dialog.addWindowListener(new java.awt.event.WindowAdapter() {
//                    @Override
//                    public void windowClosing(java.awt.event.WindowEvent e) {
//                        System.exit(0);
//                    }
//                });
//                dialog.setVisible(true);
//            }
//        });
//    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel brandErrLbl;
    private javax.swing.JTextField brandField;
    private javax.swing.JButton cancelBtn;
    private javax.swing.JLabel codeErrLbl;
    private javax.swing.JTextField codeField;
    private javax.swing.JLabel headerLabel;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel modelErrLbl;
    private javax.swing.JTextField modelField;
    private javax.swing.JButton submitBtn;
    private javax.swing.JLabel yearErrLbl;
    private javax.swing.JTextField yearField;
    // End of variables declaration//GEN-END:variables
}
